torchd.form = function(params) {
	this.init(params);
};

torchd.form.prototype.getData = function() {
	var data = [];
	for(var i=0;i<this.fields.length;i++) {
		data.push(this.fields[i].getData());
	}
	return data;

};

torchd.form.prototype.init = function(params) {
	var self = this;
	this.params = $.extend({
			buttons:{
				submit:{
					show:false,
					text:'Submit',
					onClick:false
				},
				cancel:{
					show:false,
					text:'Back',
					onClick:false
				}
			},
			message:'',
			formItems:[]
			
		},
		params);
		
	this.buttons = [];
	this.formElements = [];
	this.fields = [];
	this.domElement = $('<form/>');
	if(params.message) {
		this.message = $('<div/>').addClass('torchd-ui-form-message').html(this.params.message).appendTo(this.domElement);
	}
	this.formItems = $('<div/>').addClass('torchd-ui-form-items').appendTo(this.domElement);
	this.buttons = $('<div/>').addClass('torchd-ui-form-buttons').appendTo(this.domElement);
	
	// Go through form items and add them to the form
	for(var n=0;n<this.params.formItems.length;n++) {
		var field = new torchd.form.field(this.params.formItems[n]);
		field.appendTo(this.formItems);
		this.fields.push(field);
	}
	
	// Make buttons
	if(this.params.buttons.submit.show) {
		this.buttons.submit = $('<button/>').html(this.params.buttons.submit.text).click(function(e) {
			e.preventDefault();
			if(self.params.buttons.submit.onClick) {
				self.params.buttons.submit.onClick(self.formItems);
			}
		}).appendTo(this.buttons);
	}
	if(this.params.buttons.cancel.show) {
		this.buttons.cancel = $('<button/>').html(this.params.buttons.cancel.text).click(function(e) {
			e.preventDefault();
			if(self.params.buttons.cancel.onClick) {
				self.params.buttons.cancel.onClick();
			}
		}).appendTo(this.buttons);
	}
	
	// Return key is submit, escape key is cancel
	this.domElement.keydown(function(event) {
		if(event.keyCode == 13) {
			if(this.params.buttons.submit.show) {
				this.buttons.submit.trigger('click');
			}
		}
		else if(event.keyCode == 27) {
			if(this.params.buttons.cancel.show) {
				this.buttons.cancel.trigger('click');
			}
		}
	});
};

torchd.form.prototype.insert = function(element) {
	this.domElement.appendTo(element);
	for(var y=0;y<this.fields.length;y++) {
		this.fields[y].initSpecials();
	}
};